import { Request, Response } from "express";
import { uploadImagesToGitee } from "../services/giteeService";

export const uploadImages = async (req: Request, res: Response) => {
  try {
    console.log("收到上传请求");
    
    // 检查请求中是否包含文件
    if (!req.files) {
      console.error("请求中没有文件");
      return res.status(400).json({ error: "请求中没有文件" });
    }
    
    const files = req.files as Express.Multer.File[];
    if (files.length === 0) {
      console.error("没有上传任何文件");
      return res.status(400).json({ error: "没有上传任何文件" });
    }
    
    console.log(`收到 ${files.length} 个文件上传请求`);
    
    // 上传文件到 Gitee
    const urls = await uploadImagesToGitee(files);
    const results = urls.map((url, index) => ({
      url,
      name: files[index].originalname,
    }));
    
    console.log("文件上传成功");
    res.json({ urls: results });
  } catch (err: any) {
    console.error("上传处理过程中出错:", err);
    
    if (err.response && err.response.data) {
      console.error("API 响应错误:", err.response.data);
      res.status(500).json({ 
        error: err.response.data.message || "API 请求失败",
        details: err.response.data
      });
    } else {
      res.status(500).json({ 
        error: err.message || "服务器内部错误",
        stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
      });
    }
  }
};